package com.xingkeduo.controller.api.marketing;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xingkeduo.configuration.RedisListOpsService;
import com.xingkeduo.controller.base.InitController;
import com.xingkeduo.enums.DictMarketingEnum;
import com.xingkeduo.model.param.MarketingParam;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveSendTypeEnum;
import com.xingkeduo.model.param.VerifyReedRedeemCodeParam;
import com.xingkeduo.model.po.TDictMarketing;
import com.xingkeduo.service.api.marketing.ReceiveService;
import com.xingkeduo.service.dict.DictMarketingService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.RandomUtil;
import com.xingkeduo.util.RedisKeyEnum;
import com.xingkeduo.util.tool.ResponseMessage;

/**
 * 
* @ClassName: ReceiveController
* @Description: 用户领取记录
* @author lixin
* @date May 2, 2019 8:10:08 PM
*
 */
@RestController
@RequestMapping(Constant.API_URL_PREFIX + "/receive")
public class ReceiveController extends InitController{
	Logger logger = LoggerFactory.getLogger(ResponseMessage.class);

	@Autowired
	ReceiveService receiveService;
	@Autowired
	RedisListOpsService redisListOpsService;
	@Autowired
	DictMarketingService dictMarketingService;
	/**
	 * 
	* @Title: getUserCouponDetail 
	* @Description: 扫码获取券详情
	* @param @param marketingReceiveHistoryParam
	* @param @param request
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 2, 2019 8:32:12 PM
	 */
	@RequestMapping("/queryActivityCoupon")
	public ResponseMessage getUserCouponDetail(Long marketingId,Long userId) {
		MarketingParam marketingParam = new MarketingParam();
		marketingParam.setMarketingType(MarketingTypeEnum.COUPON.getCode());
		marketingParam.setId(marketingId);
		marketingParam.setCreateBy(userId);
		return receiveService.queryMarketingDetailById(marketingParam);
	}
	@RequestMapping("/queryActivityCard")
	public ResponseMessage getUserCardDetail(Long marketingId,Long userId) {
		MarketingParam marketingParam = new MarketingParam();
		marketingParam.setMarketingType(MarketingTypeEnum.CARD.getCode());
		marketingParam.setId(marketingId);
		marketingParam.setCreateBy(userId);
		return receiveService.queryMarketingDetailById(marketingParam);
	}
	/**
	 * 
	* @Title: queryActivityCouponBag 
	* @Description: 查看券包详情
	* @param @param marketingParamId
	* @param @param request
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 7, 2019 2:29:31 PM
	 */
	@RequestMapping("/queryActivityCouponBag")
	public ResponseMessage queryActivityCouponBag(Long marketingBagId,Long userId) {
		MarketingParam marketingParam = new MarketingParam();
		marketingParam.setMarketingType(MarketingTypeEnum.COUPON_BAG.getCode());
		marketingParam.setId(marketingBagId);
		marketingParam.setCreateBy(userId);
		return receiveService.queryCouponBagDetailById(marketingParam);
	}
	/**
	 * 
	* @Title: bindReceiveAccount 
	* @Description: 绑定领取账户 -添加领取记录-扫码领取
	* @param @param marketingReceiveHistoryParam
	* @param @param request
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 2, 2019 9:00:18 PM
	 */
	@RequestMapping("/bindReceiveAccount")
	public ResponseMessage bindReceiveAccount(@RequestBody MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		// 获取登陆用户id;
		this.initUserInParams(marketingReceiveHistoryParam);
		if(marketingReceiveHistoryParam.getMarketingId()==null) {
			return ResponseMessage.error("优惠券信息不合法", 500);
		}
		marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.SWEEP_CODE.getCode());
		return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
	}
	/**
	 * 
	* @Title: bindBagReceiveAccount 
	* @Description: 兑换码绑定-先实现预生成兑换码的业务-美团购买的先不考虑--自有兑换码
	* @param @param marketingReceiveHistoryParam
	* @param @param request
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 3, 2019 10:26:43 AM
	 */
	@RequestMapping("/bindBagReceiveAccount")
	public ResponseMessage bindBagReceiveAccount(String code,Long userId) {
		
		boolean isExcep = true;
	    long EXPIRE_TIME = 30 * 1000;
	    String keyName = RedisKeyEnum.RECEIVE_CONCURRENT_CODE_KEY.getKeyName(code);
		long _time1 = System.currentTimeMillis();
		try {
			// 创建同步锁,防止任务阻塞重复执行
			boolean locked = redisListOpsService.locked(keyName, "LOCK",EXPIRE_TIME);
			if (!locked) {
				isExcep = false;
				logger.info("【兑换码兑换】兑换中。。。。");
				return ResponseMessage.error("兑换中", 500);
			}
			return receiveService.bindBagReceiveAccount(code,userId);
		}catch(Exception e) {
			logger.error("兑换码绑定失败,e:{}",e);
			return ResponseMessage.error("操作失败", 500);
		}finally {
			if(isExcep){
				redisListOpsService.unlock(keyName);
				long _time2 = System.currentTimeMillis();
				logger.info("【兑换码兑换】解锁key： "+ keyName + "+ 耗时：" + (_time2 - _time1));
			}
		}
		
	}
	
	/**
	 * 
	* @Title: bindBagAccount 
	* @Description: 绑定券包领取账户 -添加领取记录
	* @param @param code
	* @param @param request
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 7, 2019 2:49:16 PM
	 */
	@RequestMapping("/bindBagReceiveAccountShare")
	public ResponseMessage bindBagReceiveAccountShare(Long marketingBagId) {
		MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
		marketingReceiveHistoryParam.setMarketingId(marketingBagId);
		marketingReceiveHistoryParam.setMarketingType(MarketingTypeEnum.COUPON_BAG.getCode());
		marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.SWEEP_CODE.getCode());
		// 获取登陆用户id;
		this.initUserInParams(marketingReceiveHistoryParam);
		return receiveService.bindBagReceiveAccount(marketingReceiveHistoryParam);
	}
	/**
	 * 
	* @Title: verifyUserPurchaseRedeemCode 
	* @Description: 验证兑换码 
	* @param @param verifyReedRedeemCodeParam
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 21, 2019 10:23:50 AM
	 */
	@RequestMapping("/verifyUserPurchaseRedeemCode")
	public ResponseMessage verifyUserPurchaseRedeemCode(@RequestBody VerifyReedRedeemCodeParam verifyReedRedeemCodeParam) {
		try {
			return receiveService.saveUserPurchaseRecord(verifyReedRedeemCodeParam);
		}catch(Exception e) {
			logger.error("生成核销记录异常，e:{}",e);
			return ResponseMessage.error(e.getMessage(), 500);
		}
	}
	/**
	 * 
	* @Title: bindUserPurchaseRedeemCode 
	* @Description: 绑定券包领取-美团口碑使用 
	* @param @param redeemCodeId
	* @param @param marketingId
	* @param @return    设定文件 
	* @return ResponseMessage    返回类型 
	* @throws 
	* @author lixin
	* @date May 21, 2019 10:26:29 AM
	 */
	@RequestMapping("/bindUserPurchaseRedeemCode")
	public ResponseMessage bindUserPurchaseRedeemCode(String redeemCodeId,String marketingId) {
		if(StringUtils.isBlank(redeemCodeId)) {
			return ResponseMessage.error("核销id缺失", 500);
		}
		if(StringUtils.isBlank(marketingId)) {
			return ResponseMessage.error("卡包id缺失", 500);
		}
		try {
		return receiveService.bindUserPurchaseRedeemCode(redeemCodeId,marketingId);
		}catch(Exception e) {
			logger.error("【兑换码领取异常】,e:{}",e);
			return ResponseMessage.error("领取失败", 500);
		}
	}
	
	@RequestMapping("/queryActivityCouponBagByItemId")
	public ResponseMessage queryActivityCouponBagByItemId(String itemId,Long userId) {
		if(StringUtils.isBlank(itemId)) {
			return ResponseMessage.error("套餐id缺失", 500);
		}
		if(userId==null) {
			return ResponseMessage.error("用户id缺失", 500);
		}
		MarketingParam marketingParam = new MarketingParam();
		marketingParam.setMarketingType(MarketingTypeEnum.COUPON_BAG.getCode());
		marketingParam.setThirdBizId(itemId);
		marketingParam.setCreateBy(userId);
		return receiveService.queryCouponBagDetailByItemId(marketingParam);
	}
	
	@RequestMapping("/queryMarketingBagByRedeemCode")
	public ResponseMessage queryMarketingBagByRedeemCode(String code) {
		if(StringUtils.isBlank(code)) {
			return ResponseMessage.error("参数缺失", 500);
		}
		try {
			return receiveService.queryMarketingBagByRedeemCode(code);
		}catch(Exception e) {
			return ResponseMessage.error("查询核销信息失败", 500);
		}
	}
	@RequestMapping("/queryMarketingBagByItemId")
	public ResponseMessage queryMarketingBagSurplusQuantityByItemId(String itemId) {
		if(StringUtils.isBlank(itemId)) {
			return ResponseMessage.error("参数缺失", 500);
		}
		try {
			return receiveService.queryMarketingBagSurplusQuantityByItemId(itemId);
		}catch(Exception e) {
			return ResponseMessage.error("查询核销信息失败", 500);
		}
	}
	
	@RequestMapping("/queryMarketingByHairdresserGive")
	public ResponseMessage queryMarketingByHairdresserGive() {
		try {
			return receiveService.queryMarketingByHairdresserGive();
		}catch(Exception e) {
			logger.error("获取运营营销数据失败,e:{}",e);
			return ResponseMessage.error("获取运营营销数据失败", 500);
		}
	}
	
	@RequestMapping("/bindReceiveAccountOfHairdresserGive")
	public ResponseMessage bindReceiveAccountOfHairdresserGive(MarketingReceiveHistoryParam marketingReceiveHistoryParam,String verifyCode,Long act) {
		if (marketingReceiveHistoryParam.getFromHairStyleId()==null) {
			return ResponseMessage.error("发型师id缺失", 500);
		}
		if (marketingReceiveHistoryParam.getMarketingId() == null) {
			return ResponseMessage.error("券,卡信息为空", 500);
		}
		if (marketingReceiveHistoryParam.getMarketingType() == null) {
			return ResponseMessage.error("券,卡类型为空", 500);
		}
		if (MarketingTypeEnum.parseStatus(marketingReceiveHistoryParam.getMarketingType()) == MarketingTypeEnum.UNKNOWN) {
			return ResponseMessage.error("券,卡类型未知", 500);
		}
		if(marketingReceiveHistoryParam.getUserId() == null) {
			return ResponseMessage.error("用户id缺失", 500);
		}
		if(StringUtils.isBlank(verifyCode)) {
			return ResponseMessage.error("验证码缺失", 500);
		}
		if(act == null || DateUtils.addSeconds(new Date(act), 60).before(new Date())) {
			return ResponseMessage.error("兑换链接失效", 500);
		}
		boolean isExcep = true;
		String keyName = RedisKeyEnum.RECEIVE_HAIRDRESSER_GIVE_USER_KEY.getKeyName(verifyCode);
		try {
			String lockedValue = redisListOpsService.getLockValue(keyName);
			if (StringUtils.isBlank(lockedValue)) {
				isExcep = false;
				logger.info("【发型师发券】验证码无效。。。。");
				return ResponseMessage.error("兑换链接无效", 500);
			}
			marketingReceiveHistoryParam.setCreateBy(marketingReceiveHistoryParam.getUserId());
			marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.HAIRDRESSER.getCode());
			return receiveService.bindReceiveAccountOfHairdresserGive(marketingReceiveHistoryParam);
		} catch (Exception e) {
			return ResponseMessage.error(e.getMessage(), 500);
		}finally {
			if(isExcep){
				redisListOpsService.unlock(keyName);
			}
		}
	}
	
	@RequestMapping("/getCToCShareMarketing")
	public ResponseMessage getCToCShareMarketing() {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.C_TO_C_SHARE.name(),null);
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.error("无可用邀请券", 500);
		}
		Map<String,String> returnMap = dictMarketingList.stream().filter(dictMarketing->StringUtils.isNotBlank(dictMarketing.getItemValue())).collect(Collectors.toMap(TDictMarketing::getItemCode, TDictMarketing::getItemValue));
		return ResponseMessage.ok(returnMap);
	}
	@RequestMapping("/getReceiveLink")
	public ResponseMessage getReceiveLink(Long marketingId, Integer marketingType,Long hairStyleId) {
		if(marketingId == null || marketingType == null || hairStyleId == null) {
			return ResponseMessage.error("参数缺失",500);
		}
		String code = RandomUtil.random10UUID().toLowerCase();
		String keyName = RedisKeyEnum.RECEIVE_HAIRDRESSER_GIVE_USER_KEY.getKeyName(code);
		redisListOpsService.locked(keyName, "LOCK",1*60*1000);
		String link =Constant.RECEIVE_MARKETING_PATH+"/static/sweepCode/index.html?conponId="+marketingId+"&hairStyleId="+hairStyleId+"&conponType="+marketingType+"&verifyCode="+code+"&act="+System.currentTimeMillis();
		Map<String,String> param = new HashMap();
		param.put("link", link);
		return ResponseMessage.ok(param);
	}
}
